/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.core.expand.spring.processor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;

import cn.com.ksplatform.core.expand.spring.annotation.ParentOf;

public class ParentOfBeanFactoryPostProcessor  implements
BeanFactoryPostProcessor, PriorityOrdered {

	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
			throws BeansException {
		String[] beanNames = beanFactory.getBeanDefinitionNames();
		for(String beanName : beanNames){
			//获取Bean定义
			BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
			String className = bd.getBeanClassName();
			if(!StringUtils.hasLength(className)){
				continue;
			}
			try {
				@SuppressWarnings("rawtypes")
				Class clazz = Class.forName(className);
				ParentOf po = AnnotationUtils.findAnnotation(clazz, ParentOf.class);
				if(po == null){
					continue;
				}
				bd.setParentName(po.value());
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

}
